/**
 * inforcreation.com co.Ltd
 * @author MichaelHuang
 * Nov 9, 2011
 */
package com.zchat.api.modules;

import java.util.ArrayList;
import java.util.List;

import com.zchat.api.error.ZChatModuleManagerException;
import com.zchat.api.log.Logger;
import com.zchat.api.modules.chat.SingleChatMessageManager;
import com.zchat.api.modules.system.SystemModule;
import com.zchat.api.modules.test.TestModule;

/**
 * @author Oliverzhu
 * 2012/6/13
 */
public class ModuleManagerImple implements ModuleManager {

	private List<Module> modules = new ArrayList<Module>();
	
	private static ModuleManagerImple mModuleManagerImple 
		= new ModuleManagerImple();
	
	public static ModuleManagerImple getInstance()
	{
		return mModuleManagerImple;
	}
	
	private ModuleManagerImple() {
		try {
			initialize();
		} catch (ZChatModuleManagerException e) {
			if(DEBUG)  Logger.error("实例化模块产生错误。");
		} finally {
			
		}
	}
	
	private void initialize() throws ZChatModuleManagerException {
		addModule(new SystemModule());
		addModule(new SingleChatMessageManager());
		addModule(new TestModule());
	}
	
	@Override
	public void addModule(Module module) throws ZChatModuleManagerException {
		try {
			modules.add(module);
		} catch (Exception e) {
			if(DEBUG) Logger.error(TAG+"-添加模块" + module.toString() + "产生错误。");
			removeModule(module);
			throw new ZChatModuleManagerException();
		}
	}

	@Override
	public void removeModule(Module module) throws ZChatModuleManagerException {
		try {
			modules.remove(module);
		} catch (Exception e) {
			if(DEBUG) Logger.error(TAG+"-移除模块" + module.toString() + "产生错误。");
			throw new ZChatModuleManagerException();
		}
	}

	@Override
	public List<Module> getModules() {
		return modules;
	}


	@Override
	public Module getModule(Class clazz) {
		for(Module module : modules) {
			if(module.getClass().getName().equals(clazz.getName())) {
				return module;
			}
		}
		return null;
	}

}
